﻿var Membership =
{
    _isDebugging : false,
    _isLoggedIn : false,
    _loginUrl : '',
    _logoutUrl : '',
    _sendPasswordUrl : '',
    _signUpUrl : '',
    _centerMeTimer : null,

    get_isLoggedIn : function()
    {
        return Membership._isLoggedIn; 
    },

    set_isLoggedIn : function(value)
    {
        if (Membership._isLoggedIn !== value)
        {
            Membership._isLoggedIn = value;
        }
    },

    set_loginUrl : function(value)
    {
        if (Membership._loginUrl !== value)
        {
            Membership._loginUrl = value;
        }
    },

    set_logoutUrl : function(value)
    {
        if (Membership._logoutUrl !== value)
        {
            Membership._logoutUrl = value;
        }
    },

    set_signUpUrl : function(value)
    {
        if (Membership._signUpUrl !== value)
        {
            Membership._signUpUrl = value;
        }
    },

    set_sendPasswordUrl : function(value)
    {
        if (Membership._sendPasswordUrl !== value)
        {
            Membership._sendPasswordUrl = value;
        }
    },

    init : function()
    {
        //add handlers    
//        $("#divMembershipClose").click(function(){Membership._closeButtonClick();});
        $("#txtLoginUserName").keydown(function(e){Membership._keyDownForLogin(e);});
        $("#txtLoginPassword").keydown(function(e){Membership._keyDownForLogin(e);});
        $("#txtForgotEmail").keydown(function(e){Membership._keyDownForForgotPassword(e);});

        $("#txtSignupUserName").keydown(function(e){Membership._keyDownForSignup(e);});
        $("#txtSignupPassword").keydown(function(e){Membership._keyDownForSignup(e);});
        $("#txtSignupConfirm").keydown(function(e){Membership._keyDownForSignup(e);});
        $("#txtSignupEmail").keydown(function(e){Membership._keyDownForSignup(e);});
    },

    dispose : function()
    {
        Membership._clearCenterMeTimer();

//        $removeHandler($get('divMembershipClose'), "click", Membership._closeButtonClick);

        $removeHandler($get('txtLoginUserName'), "keydown", Membership._keyDownForLogin);
        $removeHandler($get('txtLoginPassword'), "keydown", Membership._keyDownForLogin);

        $removeHandler($get('txtForgotEmail'), "keydown", Membership._keyDownForForgotPassword);

        $removeHandler($get('txtSignupUserName'), "keydown", Membership._keyDownForSignup);
        $removeHandler($get('txtSignupPassword'), "keydown", Membership._keyDownForSignup);
//        $removeHandler($get('txtSignupConfirm'), "keydown", Membership._keyDownForSignup);
        $removeHandler($get('txtSignupEmail'), "keydown", Membership._keyDownForSignup);
    },

    _show : function()
    {

        $("#divMembershipBox").modal({overlay:50});
    },

    _hide : function()
    {
//        $("#divDimBackground").hide();
//        $("#divMembershipBox").hide();
        $.modal.close();
    },

    showLogin : function()
    {
        $("#divSignup").hide();
        $("#divLogin").show();

        //hide validators and messages
        $("#divMembershipBox span.validator").hide();
        $("#divMembershipBox span.validator").text('');
        $("#divMembershipBox span.message").hide();
        
        //reset intputs
        $("#divMembershipBox :text").val("");
        $("#divMembershipBox :password").val("");
        $("#divMembershipBox :checkbox").each(function ()
                                                { this.checked = false;});
        
        Membership._show();
        $("#txtLoginUserName").focus();
        if(Membership._isDebugging)
        {
            $("#txtLoginUserName").val("");
            $("#txtLoginPassword").val("");
        }
    },

    login : function()
    {
        $("#divLogin span.validator").hide();
        $("#loginMessage").hide();

        var txtUserName = $('#txtLoginUserName');
        var userName = $.trim(txtUserName.val());
        
        if (userName.length == 0)
        {
            Membership._showMessage('#valLoginUserName', 'User name cannot be blank.', true);
            $(txtLoginUserName).focus();
            return;
        }

        var txtPassword = $('#txtLoginPassword');
        var password = txtPassword.val();

        if (password.length == 0)
        {
            Membership._showMessage('#valLoginPassword', 'Password cannot be blank.', true);
            $(txtLoginPassword).focus();
            return;
        }

        var rememberMe = $('#chkLoginRememberMe').is(":checked");// = $('#chkLoginRememberMe').checked;
        
        Membership._showMessage('#loginMessage', 'Authenticating...', false);
        $('#btnLogin').attr("disabled","disabled");

        $.ajax({ 
                        type: "POST",
                        dataType: "json",
                        url: Membership._loginUrl,
                        data: {userName: userName, password: password, rememberMe:rememberMe},
                        success:function(result)
                        {
                            $('#btnLogin').removeAttr("disabled");

                            if (result.isSuccessful == true)
                            {
                                window.location.reload();
                            }
                            else
                            {
                                Membership._showMessage('#loginMessage', result.errorMessage, true);
                                $('#txtLoginUserName').focus();
                            }
                        },
                        error:function(error)
                        {
                            $('#btnLogin').removeAttr("disabled");
                            $('#txtLoginUserName').focus();
                            Membership._showMessage('#loginMessage', 'An unexpected error has occurred while logging in.', true);
                        }
                });
    },

    logout : function()
    {
    
        $.post(
                        Membership._logoutUrl,
                        null,
                        function(result)
                        {
                            if (result.isSuccessful == true)
                            {
                                window.location.reload();
                            }
                        },
                        "json"
                    );
    },
    
    sendPassword : function()
    {
        $("#divLogin span.validator").hide();
        $("#passwordMessage").hide();

        var txtEmail = $('#txtForgotEmail');
        var email = $.trim(txtEmail.val());

        if (email.length == 0)
        {
            Membership._showMessage('#valForgotEmail', 'Email cannot be blank.', true);
            $(txtEmail).focus();
            return;
        }

        if (!Membership._isValidEmail(email))
        {
            Membership._showMessage('#valForgotEmail', 'Invalid email address.', true);
            $(txtEmail).focus();
            return;
        }

        Membership._showMessage('#passwordMessage', 'Sending password...', false);
        $('#btnPassword').attr("disabled","disabled");
        $.ajax({ 
                type: "POST",
                dataType: "json",
                url: Membership._sendPasswordUrl,
                data: {email: email},
                success:function(result)
                {
                    $("#passwordMessage").hide();
                    $('#btnPassword').removeAttr("disabled");

                    if (result.isSuccessful == true)
                    {
                        Membership._hide();
                    }
                    else
                    {
                        Membership._showMessage('#valForgotEmail', result.errorMessage, true);
                        $(txtEmail).focus();
                    }
                },
                error:function(error)
                {
                    $('#btnPassword').removeAttr("disabled");
                    Membership._showMessage('#passwordMessage', 'An unexpected error has occurred while sending the password.', true);
                }
        });       
    },

    showSignUp : function()
    {
        $("#divLogin").hide();
        $("#divSignup").show();
        //hide validators and messages
        $("#divMembershipBox span.validator").hide();
        $("#divMembershipBox span.validator").text('');
        $("#divMembershipBox span.message").hide();
        //reset intputs
        $("#divMembershipBox :text").val("");
        $("#divMembershipBox :password").val("");
//        $("#divMembershipBox :checkbox").each(function ()
//                                                { this.checked = false;});
        Membership._show();
        $("#txtSignupUserName").focus();
        if(Membership._isDebugging)
        {
            $("#txtSignupUserName").val("");
            $("#txtSignupPassword").val("");
            $("#txtSignupEmail").val("");
        }        
        
    },

    signUp : function()
    {
        $("#divSignup span.validator").hide();
        $("#signupMessage").hide();

        var txtUserName = $('#txtSignupUserName');
        var userName = $.trim(txtUserName.val());

        if (userName.length == 0)
        {
            Membership._showMessage('#valSignupUserName', 'User name cannot be blank.', true);
            $(txtLoginUserName).focus();
            return;
        }

        var txtPassword = $('#txtSignupPassword');
        var password = txtPassword.val();

        if (password.length < 4)
        {
            Membership._showMessage('#valSignupPassword', 'Password must be 4 character long.', true);
            $(txtLoginPassword).focus();
            return;
        }

        var txtEmail = $('#txtSignupEmail');
        var email = $.trim(txtEmail.val());

        if (email.length == 0)
        {
            Membership._showMessage('#valSignupEmail', 'Email cannot be blank.', true);
            $(txtEmail).focus();
            return;
        }

        if (!Membership._isValidEmail(email))
        {
            Membership._showMessage('#valSignupEmail', 'Invalid email address.', true);
            $(txtEmail).focus();
            return;
        }

        var formFields = [['userName', userName],['password', password],['email', email]];

        Membership._showMessage('#signupMessage', 'Signing up...', false);
        $('#btnSignup').attr("disabled","disabled");
        
        $.ajax({ 
                type: "POST",
                dataType: "json",
                url: Membership._signUpUrl,
                data: {userName: userName, password: password, email:email},
                success:function(result)
                {
                   $('#btnSignup').removeAttr("disabled");

                    if (result.isSuccessful == true)
                    {
                        Membership._hide();
                        window.location.reload();
                    }
                    else
                    {
                        var msg = result.errorMessage;
                        $("#signupMessage").hide();

                        if (msg.indexOf('username') > -1)
                        {
                            Membership._showMessage('#valSignupUserName', msg, true);
                            $(txtSignupUserName).focus();
                        }
                        else if (msg.indexOf('E-mail') > -1)
                        {
                            Membership._showMessage('#valSignupEmail', msg, true);
                            $(txtSignupEmail).focus();
                        }
                        else
                        {
                            Membership._showMessage('#signupMessage', msg, true);
                        }
                    }
                },
                error:function(error)
                {
                    $('#btnSignup').removeAttr("disabled");
                    Membership._showMessage('#signupMessage', 'An unexpected error has occurred while signning up.', true);
                }
        });
    },

    _showMessage : function(e, msg, err)
    {
        //var e = $U.fix(e);
        if (err)
        {
            $(e).css("color" ,'#ff0000');
        }
        else
        {
            $(e).css("color", '');
        }
        $(e).text(msg);
        $(e).show();
    },

    _isValidEmail : function(email)
    {
        var regExp = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        return regExp.test(email);
    },

    _keyDownForLogin : function(e)
    {
        if (e.keyCode === keys.enter)
        {
            Membership.login();
        }
        else if (e.keyCode === keys.esc)
        {
            Membership._hide();
        }
    },

    _keyDownForForgotPassword : function(e)
    {
        if (e.keyCode === keys.enter)
        {
            Membership.sendPassword();
        }
        else if (e.keyCode === keys.esc)
        {
            Membership._hide();
        }
    },

    _keyDownForSignup : function(e)
    {
        if (e.keyCode === keys.enter)
        {
            Membership.signUp();
        }
        else if (e.keyCode === keys.esc)
        {
            Membership._hide();
        }
    },

    _closeButtonClick : function(e)
    {
        Membership._hide();
    }
    
       
}

var Friends =
{

    init : function()
    {
        //add handlers    
        $("#txtFindFriends").keydown(function(e){Friends._keyDownForSearch(e);});
        $("#txtInviteFriends").keydown(function(e){Friends._keyDownForInvite(e);});
    },
    
    _keyDownForSearch : function(e)
    {
        if (e.keyCode === keys.enter)
        {
            Friends.find();
        }
    },
    
    _keyDownForInvite : function(e)
    {
        if (e.keyCode === keys.enter)
        {
            Friends.invite();
        }
    },

    follow : function(userid)
    {
        var lnk = $("#lnkFollow" + userid);
        
        if (lnk.attr("lnktype") == "unfollow")
            return Friends.unfollow(userid);            
        lnk.hide();
        var url = "/user/follow";
        $.ajax({ 
                type: "POST",
                dataType: "json",
                url: url,
                data: {userid: userid},
                success:function(result)
                {
                    if (result.isSuccessful == true)
                    {
                        lnk.addClass("hilite").fadeOut(1000, function(){
                                    lnk.fadeIn(1000, function(){lnk.removeClass("hilite")});
                                    lnk.html("un-follow");
                                    lnk.attr("lnktype", "unfollow");
                                    });
                                                         
                    }
                    else
                    {
                        alert(result.errorMessage);
                    }
                },
                error:function(error)
                {
                    alert(result.errorMessage);
                }
            });
    },
    
    unfollow : function(userid)
    {
        var lnk = $("#lnkFollow" + userid);
        if (lnk.attr("lnktype") == "follow")
            return Friends.follow(userid);
        lnk.hide();
            
        var url = "/user/unfollow";
        $.ajax({ 
                type: "POST",
                dataType: "json",
                url: url,
                data: {userid: userid},
                beforeSend:function()
                {
                },
                success:function(result)
                {
                    if (result.isSuccessful == true)
                    {
                        
                        lnk.addClass("hilite").fadeOut(1000, function(){
                                    lnk.fadeIn(1000, function(){lnk.removeClass("hilite")});
                                    lnk.html("follow");
                                    lnk.attr("lnktype", "follow");
                        });
                    }
                    else
                    {
                        alert(result.errorMessage);
                    }
                },
                error:function(error)
                {
                    alert(result.errorMessage);
                }
            });
    },
    
    find : function()
    {
        var txtFindFriends = $("#txtFindFriends");
        window.location = "/user/find?searchTerm=" + txtFindFriends.val();   
    },
    
    invite : function()
    {   
        var txt = $("#txtInviteFriends");
        var msg = $("#inviteMessage");
        var btn = $("#btnInvite");
        msg.hide();
        
        var email = $.trim(txt.val());
        if (email.length == 0)
        {
            Friends._showMessage(msg, 'Email cannot be blank.');
            txt.focus();
            return;
        }

        if (!Membership._isValidEmail(email))
        {
            Friends._showMessage(msg, 'Invalid email address.');
            txt.focus();
            return;
        }
        
        msg.html("sending invitation...").show();
        txt.attr("disabled","disabled");
        btn.attr("disabled","disabled");
        $.ajax({ 
                type: "POST",
                dataType: "json",
                url: "friends/invite",
                data: {email: email},
                success:function(result)
                {
                    if (result.isSuccessful == true)
                    {
                        Friends._showMessage(msg, "invitation sent.");
                        msg.fadeIn(1000, function(){msg.fadeOut(7000, function(){
                                                        txt.val("");
                                                        txt.removeAttr("disabled"); 
                                                        btn.removeAttr("disabled");
                                            })
                                            }
                                    );
                    }
                    else
                    {
                        Friends._showMessage(msg, result.errorMessage);
                        txt.removeAttr("disabled"); 
                        btn.removeAttr("disabled");
                    }
                },
                error:function(error)
                {
                    Friends._showMessage(msg, "Unexpected error.");
                    txt.removeAttr("disabled"); 
                    btn.removeAttr("disabled");
                }
            });
    },
    
    _showMessage : function (e, msg)
    {
        e.fadeOut(1000, function(){
                    e.addClass("hilite");
                    e.html(msg);
                    e.fadeIn(1000);
        });
    }
    
}
var TwitterFriends =
{
  invite: function(twitterusername) {

    var lnk = $("#lnkInvite" + twitterusername);

    if (lnk.attr("lnktype") == "invited") {
      return;
    }
    lnk.hide();

    $("#progess" + twitterusername).attr("src", "/Content/Images/progress.gif").show();

    var url = "/twitterfriends/invite/" + twitterusername;
    $.ajax({
      type: "POST",
      dataType: "json",
      url: url,
      data: { twitterusername: twitterusername },
      success: function(result) {
        if (result.isSuccessful == true) {
          lnk.addClass("hilite").fadeOut(2000, function() {
            lnk.fadeIn(2000, function() { lnk.removeClass("hilite") });
            lnk.html("Invitation Send");
            lnk.href = "#";
            $("#progess" + twitterusername).hide();
            lnk.attr("lnktype", "invited");
          });

        }
        else {
          alert(result.errorMessage);
          $("#progess" + twitterusername).hide();
          lnk.show("slow");
        }
      },
      error: function(error) {
        alert(result.errorMessage);
      }
    });
  },
  find: function(twitterusername) {
    window.location = "/twitterfriends/" + twitterusername;
  }
}